package ua.yandex.skipass;

import java.util.Arrays;
import java.util.Calendar;

public class DateChecker {

    public static final int NUMBER_HOURS_IN_DAY = 24;
    public static final int NUMBER_DAYS_IN_WEEK = 7;
    private boolean[] validHours = new boolean[NUMBER_HOURS_IN_DAY];
    private boolean[] validDays = new boolean[NUMBER_DAYS_IN_WEEK];

    private void validNumberOfDay(int numberOfDay) {
        if (numberOfDay > Calendar.SATURDAY || numberOfDay < Calendar.SUNDAY) {
            throw new IllegalArgumentException("Invalid number of day!");
        }
    }

    private void validIndexOfHour(int indexOfHour) {
        if (indexOfHour >= NUMBER_HOURS_IN_DAY || indexOfHour < 0) {
            throw new IllegalArgumentException("Invalid index of hour!");
        }
    }

    public void setDayAsValid(int numberOfDay) {
        validNumberOfDay(numberOfDay);
        int indexOfDay = numberOfDay - 1;
        validDays[indexOfDay] = true;
    }

    public void setHourAsValid(int indexOfHour) {
        validIndexOfHour(indexOfHour);
        validHours[indexOfHour] = true;
    }

    public void setHoursAsValid(int validFromHour, int validUntilHour) {
        validIndexOfHour(validFromHour);
        validIndexOfHour(validUntilHour);
        for (int indexOfHour = validFromHour; indexOfHour <= validUntilHour;
                indexOfHour++) {
            validHours[indexOfHour] = true;
        }
    }

    public void resetHours() {
        validHours = new boolean[NUMBER_HOURS_IN_DAY];
    }

    public void resetDays() {
        validDays = new boolean[NUMBER_HOURS_IN_DAY];
    }

    public boolean validAt(Calendar someTime) {
        int someDay = someTime.get(Calendar.DAY_OF_WEEK);
        int indexOfDay = someDay - 1;
        int indexOfHour = someTime.get(Calendar.HOUR_OF_DAY);
        if (validDays[indexOfDay]) {
            if (validHours[indexOfHour]) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean equals(Object someObject) {
        if (!(someObject instanceof DateChecker)) {
            return false;
        }
        if (Arrays.equals(((DateChecker) someObject).validHours, validHours)) {
            if (Arrays.equals(((DateChecker) someObject).validDays, validDays)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int hashCode() {
        return 0;
    }

    public DateChecker makeEqual() {
        DateChecker newChecker = new DateChecker();
        java.lang.System.arraycopy(
                validDays, 0, newChecker.validDays, 0, validDays.length);
        java.lang.System.arraycopy(
                validHours, 0, newChecker.validHours, 0, validHours.length);
        return newChecker;
    }

}